<template>
  <div class="app-container">
    <div class="left">
      <el-input v-model="req.key" class="mb20" placeholder="输入关键字过滤" @change="filterChange"></el-input>
      <el-tree class="tree-box" ref="tree" node-key="id" :data="deptTree" :props="{ label: 'alias', children: 'children' }" :filter-node-method="filterNode" :default-expand-all="true" :highlight-current="true" :check-on-click-node="true" :expand-on-click-node="false" @node-click="deptChange">
        <div class="custom-tree-node" slot-scope="{ node, data }">
          <div>{{ node.label }}</div>
          <div>
            <el-button v-if="data.leaf!=1" circle size="mini" icon="el-icon-plus" @click.stop="addDept(data)"></el-button>
            <el-button circle size="mini" :disabled="deptTree.length && deptTree[0].path == data.path" icon="el-icon-minus" @click.stop="delDept(data)"></el-button>
            <el-button circle size="mini" icon="el-icon-edit" @click.stop="editDept(data)"></el-button>
          </div>
        </div>
      </el-tree>
    </div>
    <div class="right">
        <div class="table-list">
        <el-row :gutter="20" class="mb20" style="margin-right: 0;">
            <el-col :span="6"><el-input v-model="req._mobile_" type="text" placeholder="请输入手机号" @change="getUserList"></el-input></el-col>
            <el-col :span="6"><el-input v-model="req._name_" type="text" placeholder="请输入姓名" @change="getUserList"></el-input></el-col>
            <el-col :span="6">
            <el-button type="primary" icon="el-icon-search" @click="getUserList">查询</el-button>
            <el-button type="success" icon="el-icon-plus" @click="addUser">新增</el-button>
            </el-col>
        </el-row>
        <el-table :data="userList" border style="width: 100%">
            <el-table-column type="index" label="序号" width="60" align="center" show-overflow-tooltip>
            <template slot-scope="{ $index }">
                {{ $index + 1 + (req.page - 1) * req.pageSize }}
            </template>
            </el-table-column>
            <el-table-column prop="name" label="姓名" align="left" show-overflow-tooltip></el-table-column>
            <el-table-column prop="userName" label="账号" min-width="120" align="left" show-overflow-tooltip></el-table-column>
            <el-table-column prop="mobile" label="手机号" min-width="120" align="left" show-overflow-tooltip></el-table-column>
            <el-table-column prop="code" label="工号" min-width="120" align="left" show-overflow-tooltip></el-table-column>
            <el-table-column prop="groupName" label="部门" align="left" show-overflow-tooltip></el-table-column>
            <!-- <el-table-column prop="gmtCreate" label="创建时间" min-width="120" align="left" show-overflow-tooltip></el-table-column> -->
            <el-table-column prop="validate" label="状态" min-width="80" align="left" show-overflow-tooltip>
            <template slot-scope="{ row }">
                <!-- <span>{{ row.validate == 1 ? '启用' : row.validate == 0 ? '未启用' : '已关闭' }}</span> -->
                <el-tag type="success" v-if="row.validate==1" size="mini">已启用</el-tag>
                <el-tag type="warning" v-else-if="row.validate==0" size="mini">未启用</el-tag>
                <el-tag type="danger" v-else size="mini">已关闭</el-tag>
            </template>
            </el-table-column>
            <el-table-column label="操作" width="180" align="center">
            <template slot-scope="{ row }">
                <el-button @click="updatePass(row)" type="text" size="small">修改密码</el-button>
                <el-button @click="editUser(row)" type="text" size="small">编辑</el-button>
                <!-- <el-button @click="delUser(row)" type="text" size="small">删除</el-button> -->
                <el-button @click="switchAccount(row)" type="text" size="small">{{row.validate == 1 ? '关闭':'启用'}}</el-button>
            </template>
            </el-table-column>
        </el-table>
        <Pagination v-show="total" :total="total" :page.sync="req.page" :limit.sync="req.pageSize" @pagination="getUserList"></Pagination>
        </div>
        <div class="" style="height: 100%;flex: 1 0 25vw;">
            <Map ref="map" style="width: 100%;height: 100%;"></Map>
        </div>
    </div>

    <!-- 弹窗 -->
    <deptEdit :show.sync="showDeptEdit" :item="currentDept" @change="getDeptTree"></deptEdit>
    <userEdit :show.sync="showUserEdit" :item="currentUser" @change="getUserList"></userEdit>
    <updatePassVue :visiblePass="visiblePass" @confirm="onConfirmPass" @close="visiblePass = false"></updatePassVue>
  </div>
</template>

<script>
import Map from '@/components/Map'
import deptEdit from "./components/deptEdit.vue";
import userEdit from "./components/userEdit.vue";
import updatePassVue from "./components/updatePass.vue";

import {
  groupDel,
  groupTree,
  memberList,
  memberDel,
  memberChangPwd,
  closeAccount,
  openAccount
} from "@/api/user";
export default {
  name: "Account",
  components: {
    deptEdit,
    userEdit,
    updatePassVue,
    Map
  },
  data() {
    return {
      showDeptEdit: false,
      showUserEdit: false,

      currentDept: {},
      currentUser: null,

      deptTree: [],
      userList: [],

      total: 0,
      req: {
        groupPath: null,
        _name_: null,
        _mobile_: null,
        orderBy: "id desc",
        validate: null, //0未启用，1启用, -1 已关闭
        page: 1,
        pageSize: 10,
      },

      visiblePass: false,
    };
  },
  created() {
    // 缓存租户信息，动态设置用户扩展字段
    this.$store.dispatch("getTenantInfo");
    this.getDeptTree();
    this.getUserList();
  },
  methods: {
    // 获取部门树
    getDeptTree() {
      groupTree().then((res) => {
        this.deptTree = res.data || [];
      });
    },
    // 获取部门下的用户
    getUserList() {
      memberList(this.req).then((res) => {
        this.userList = res.data || [];
        this.total = res.total;
      });
    },
    filterChange(e) {
      console.log(e);
      this.$refs.tree.filter(e);
    },
    // 过滤部门树
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // 部门选中发生改变
    deptChange(data, node) {
      if (this.req.groupPath == data.path && this.currentDept.id) return;
      this.req.page = 1;
      this.req.groupPath = data.path;
      this.currentDept = JSON.parse(JSON.stringify(data));
      this.getUserList();
      console.log(data)
      if (!this.$refs.map || !this.$refs.map.map) return;
      this.$refs.map.remove();
      if(!data.area) return;
      this.$refs.map.createPolygonLayers(JSON.parse(data.area));
    },
    // 新增部门
    addDept(data, event) {
      // 弹窗输入内容
      this.currentDept = {
        parent: data.id,
      };
      this.showDeptEdit = true;
      this.$refs.tree.setCurrentKey();
      // 刷新部门树
      this.getDeptTree();
    },
    // 删除部门
    delDept(data,event) {
      if (this.deptTree.length <= 1) {
        const firstParent = this.deptTree[0];
        if (firstParent.path == data.path) {
          return this.$message.error("根数据不可删除！");
        }
      }
      this.$modal
        .confirm("确定删除此条数据吗？")
        .then((res) => {
          // 请求服务器删除数据
          groupDel({
            id: data.id,
          }).then((res) => {
            // 如果是当前选中就清空右侧数据
            if (data.id == this.req.dept) {
              this.userList = [];
            }
            // 刷新节点
            this.getDeptTree();
          });
        })
        .catch((e) => {
          console.log("取消删除-----");
        });
    },
    // 编辑部门
    editDept(data, event) {
      this.currentDept = JSON.parse(JSON.stringify(data));
      this.showDeptEdit = true;
    },
    // 添加用户
    addUser() {
      if (!this.currentDept.id) {
        this.$modal.msgError("请先选择部门");
        return;
      }
      this.currentUser = {
        groupId: this.currentDept.id,
        groupName: this.currentDept.name,
        groupPath: this.currentDept.path,
      };
      this.showUserEdit = true;
    },
    // 切换账户状态
    switchAccount(row) {
        const msg = row.validate == 1?'确定关闭此账户吗？':'确定开启此账户吗？'
        this.$modal.confirm(msg).then(res => {
            return row.validate == 1?closeAccount({memberId: row.id}):openAccount({memberId: row.id})
        }).then(res => {
            if(res.code == 1) {
                this.$message.success("操作成功！")
                this.getUserList()
            }
        })
    },
    // 删除用户
    delUser(row) {
      this.$modal.confirm("确定删除此条数据吗？").then((res) => {
        // 请求服务器删除数据
        memberDel({
          id: row.id,
        }).then((res) => {
          // 刷新数据
          this.getUserList();
        });
      });
    },
    // 修改用户
    editUser(row) {
      this.currentUser = JSON.parse(JSON.stringify(row));
      this.showUserEdit = true;
    },

    updatePass(row) {
      this.currentUser = JSON.parse(JSON.stringify(row));
      this.visiblePass = true;
    },
    onConfirmPass(value) {
      memberChangPwd({
        memberId: this.currentUser.id,
        newPwd: value,
      }).then((res) => {
        this.visiblePass = false;
        this.$modal.msgSuccess("密码修改成功");
      });
    },
    onRowClick(row) {
        console.log(row)
    }
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;

  .left {
    width: 300px;
    margin-right: 20px;
    overflow: auto;
    .tree-box {
      overflow-y: auto;
      height: calc(100vh - 250px);
      padding: 10px 0;
      border-radius: 5px;
    }
    .custom-tree-node {
      display: flex;
      align-items: center;
    }
  }

  .right {
    flex: 1;
    overflow: auto;
    display: flex;
    justify-content: space-between;
    .table-list {
    }
  }
}
</style>
<style lang="scss">
.app-container {
  .left {
    .el-button--mini.is-circle {
      padding: 3px;
      margin-left: 3px;
    }

    .el-tree--highlight-current
      .el-tree-node.is-current
      > .el-tree-node__content {
      background-color: rgb(83, 143, 252);
      color: #fff;
      border-radius: 3px;
    }
  }
}
</style>
